package com.zhangzy.qm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {
		  
	    public static void zip(String souceFileName, String destFileName) {  
	    	System.out.println("zip file start:" + destFileName);  
	        File file = new File(souceFileName);  
	        try {  
	            zip(file, destFileName);  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	        System.out.println("zip file end:" + destFileName);  
	    }  
	  
	    public static void zip(File souceFile, String destFileName) throws IOException {  
	        FileOutputStream fileOut = null; 
	        ZipOutputStream out = null; 
	        try {  
	            fileOut = new FileOutputStream(destFileName);  
		        out = new ZipOutputStream(fileOut);  
		        zip(souceFile, out, "");  
	        } catch (FileNotFoundException e) {  
	            e.printStackTrace();  
	        }finally{
	        	if(out!=null){
	        		 out.close();  
	        	}
	        	if(fileOut!=null){
	        		fileOut.close();
	        	}
	        }   
	    }  
	  
	    public static void zip(File souceFile, ZipOutputStream out, String base)  
	            throws IOException {  
	  
	        if (souceFile.isDirectory()) {  
	            File[] files = souceFile.listFiles();  
	            out.putNextEntry(new ZipEntry(base + "/"));  
	            base = base.length() == 0 ? "" : base + "/";  
	            for (File file : files) {  
	                zip(file, out, base + file.getName());  
	            }  
	        } else {  
	            if (base.length() > 0) {  
	                out.putNextEntry(new ZipEntry(base));  
	            } else {  
	                out.putNextEntry(new ZipEntry(souceFile.getName()));  
	            }  
	            FileInputStream in = new FileInputStream(souceFile);  
	  
	            int b;  
	            byte[] by = new byte[1024];  
	            while ((b = in.read(by)) != -1) {  
	                out.write(by, 0, b);  
	            }  
	            in.close();  
	        }  
	    }  
	  
	    /** 
	     * Test 
	     */  
	    public static void main(String[] args) {  
	    	ZipUtil z = new ZipUtil();  
	        z.zip("D:\\temp", "D:/Data.zip");  
//	    	int num =(int) (Math.round((Math.random()*100))%10);
//	    	System.out.println(num);
	    }  
}
